<template>
  <view class="container">
    <!-- 头部 -->
    <!-- <view class="header">
      <image 
        class="back-icon" 
        src="/static/img/icon-Get-into@3.png" 
        mode="aspectFit"
        @click="goBack"
      />
      <view class="header-title">
        <text>新手机号</text>
      </view>
    </view> -->
    
    <!-- 主体内容 -->
    <view class="wrapper">
      <view class="change">
        <view class="cont">
          <!-- 手机号输入 -->
          <view class="input-item">
            <image 
              class="input-icon" 
              :src="serverAddress+'img/login/icon-iphone@2x.png'" 
              mode="aspectFit"
            />
            <input 
              type="number" 
              v-model="phoneNew" 
              maxlength="11" 
              placeholder="请输入新手机号" 
              class="input-field"
            />
          </view>
          
          <!-- 验证码输入 -->
          <view class="input-item">
            <image 
              class="input-icon verify-icon" 
              :src="serverAddress+'img/login/icon-xinxi@2x.png'" 
              mode="aspectFit"
            />
            <input 
              type="number" 
              v-model="verifyCode" 
              placeholder="短信验证码" 
              class="input-field"
            />
            <button 
              class="verify-btn" 
              :disabled="btnDisabled" 
              @click="sendVerifyCode"
            >
              {{ btnText }}
            </button>
          </view>
        </view>
        
        <!-- 完成按钮 -->
        <button class="submit-btn" :style="{'backgroundImage': `url(${serverAddress}img/login/Button-@2x.png)`}" @click="changePhone">完成</button>
      </view>
    </view>
  </view>
</template>

<script>
import { userApi } from '@/api/index.js'
import { getCurrentUser } from '@/api/auth.js'
import {
		inject
	} from 'vue'
export default {
  data() {
    return {
		serverAddress: inject('$serverAddress'),
      phoneNew: '', // 新手机号
      verifyCode: '', // 验证码
      ordertime: 60, // 再次发送验证码等待时间
      timeleft: 60, // 剩余时间
      btnDisabled: false, // 按钮是否禁用
      btnText: '发送验证码', // 按钮文字
      ip: '' // IP地址
    }
  },
  
  onLoad() {
    this.getIp()
  },
  
  methods: {
    // 获取IP地址
    async getIp() {
      try {
        const res = await userApi.getIp()
        if (res.r === 0) {
          this.ip = res.data
        }
      } catch (error) {
        console.error('获取IP地址失败:', error)
      }
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 计时函数
    timeCount() {
      this.timeleft -= 1
      if (this.timeleft > 0) {
        this.btnText = `${this.timeleft} 秒后重发`
        setTimeout(() => {
          this.timeCount()
        }, 1000)
      } else {
        this.btnText = '重新发送'
        this.timeleft = this.ordertime // 重置等待时间
        this.btnDisabled = false
      }
    },
    
    // 发送验证码
    async sendVerifyCode() {
      // 验证手机号
      if (!this.phoneNew) {
        uni.showToast({
          title: '手机号不能为空',
          icon: 'none',
          duration: 1500
        })
        return
      }
      
      const reg = /^1[0-9]\d{9}$/
      if (!reg.test(this.phoneNew)) {
        uni.showToast({
          title: '手机号格式错误',
          icon: 'none',
          duration: 1500
        })
        return
      }
      
      try {
        // 检查手机号是否已注册
        const checkRes = await userApi.checkMobile({ mobile: this.phoneNew })
        
        if (!checkRes.data.is_used) {
          // 手机号未被使用，可以发送验证码
          const codeRes = await userApi.sendMobileCodeForChange({
            mobile: this.phoneNew,
            last_login_ip: this.ip || '0.0.0.0'
          })
          
          if (codeRes.r === 0) {
            this.btnDisabled = true
            this.timeCount()
            uni.showToast({
              title: codeRes.msg || '验证码发送成功',
              icon: 'success'
            })
          } else {
            uni.showToast({
              title: codeRes.msg || '验证码发送失败',
              icon: 'none'
            })
          }
        } else {
          uni.showToast({
            title: checkRes.msg || '该手机号已被使用',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('发送验证码失败:', error)
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        })
      }
    },
    
    // 更换手机号
    async changePhone() {
      if (!this.phoneNew.trim()) {
        uni.showToast({
          title: '手机号不能为空',
          icon: 'none',
          duration: 1500
        })
        return
      }
      
      if (!this.verifyCode.trim()) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        })
        return
      }
      
      try {
        const res = await userApi.changePhone({
          mobile: this.phoneNew,
          code: this.verifyCode,
          last_login_ip: this.ip
        })
        
        if (res.r === 0) {
          uni.showToast({
            title: res.msg || '手机号更换成功',
            icon: 'success'
          })
          
          // 保存新手机号到本地存储
          uni.setStorageSync('newPhone', this.phoneNew)
          
          // 返回上一页或跳转到个人中心
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: res.msg || '手机号更换失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('更换手机号失败:', error)
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  width: 100%;
  min-height: 100vh;
  background-color: #F6F6F6;
}



/* 主体内容 */
.wrapper {
  padding: 30rpx 30rpx 0;
}

.cont {
  width: 100%;
  margin-top: 30rpx;
}

.input-item {
  position: relative;
  width: 100%;
  height: 96rpx;
  border-radius: 4rpx;
  background-color: white;
  border: 2rpx solid #F0F0F0;
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
}

.input-item:last-child {
  margin-bottom: 0;
}

.input-icon {
  position: absolute;
  left: 30rpx;
  width: 34rpx;
  height: 50rpx;
  z-index: 1;
}

.verify-icon {
  top: 22rpx;
  width: 40rpx;
}

.input-field {
  flex: 1;
  height: 100%;
  border: 0;
  padding-left: 80rpx;
  padding-right: 20rpx;
  font-size: 32rpx;
  background-color: white;
  box-sizing: border-box;
}

.verify-btn {
  position: absolute;
  right: 26rpx;
  // top: 44rpx;
  padding: 0 28rpx;
  height: 57rpx;
  border: 2rpx solid #37A962;
  color: #37A962;
  font-size: 32rpx;
  border-radius: 4rpx;
  background-color: white;
  line-height: 57rpx;
}

.verify-btn:disabled {
  opacity: 0.6;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  height: 108rpx;
  border: 0;
  border-radius: 10rpx;
  margin-top: 56rpx;
  color: white;
  font-size: 38rpx;
  /* background-image: url('/static/img/login/Button-@2x.png'); */
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>